package com.zelin.model3;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * TCP通信:
 * 客户端
 */
public class TcpClient {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        Socket socket =null;
        OutputStream outputStream =null;
        InputStream inputStream =null;
        ObjectOutputStream oos=null;

        //创建客户端对象,指定连接的主机IP和端口
        try {
            socket = new Socket("192.168.5.1", 6666);
            System.out.println("客户端已经创建");

            //获得字节数出流对象
            outputStream = socket.getOutputStream();
            oos=new ObjectOutputStream(outputStream);

            System.out.print("请输入用户名:");
            String name=scanner.next();
            System.out.print("请输入密码:");
            String password=scanner.next();
            //发送消息给客户端
            User user = new User(name, password);
            oos.writeObject(user);

            //从服务端接受数据,返回密码的正确与否
            inputStream = socket.getInputStream();
            byte[] b=new byte[1024];
            int read = inputStream.read(b);
            String string=new String(b);
            System.out.println("服务端:"+string);


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                assert inputStream != null;
                inputStream.close();
                oos.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
